package com.liu.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.liu.auth.feign.api.ShopCarServices;
import com.liu.auth.feign.api.UserServices;
import com.liu.shop.common.constant.AuthConstants;
import com.liu.shop.common.vo.ThirdUser;
import com.liu.shop.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 第三方登录
 */
@Controller
@RequestMapping("/oauth")
@Slf4j
public class ThirdLoginController {

    @Autowired
    private UserServices userServices;

    @Autowired
    private ShopCarServices shopCarServices;

    /**
     * 用户点击第三方登录，跳转到授权页面
     * @param response
     * @throws IOException
     */
    @RequestMapping("/login")
    public void login(HttpServletResponse response) throws IOException {
        // 1.获取在第三方授权注册的应用的信息(id，重定向的url)
        AuthRequest authRequest = getAuthRequest();

        // 2.获取引导应用授权的地址
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.debug("所引导的授权地址为:{}", authorizeUrl);

        // 3.重定向到授权页面
        response.sendRedirect(authorizeUrl);
    }

    /**
     * 回调方法,可以拿到第三方用户的基本信息
     * @param callback
     * @param request
     * @return
     */
    @RequestMapping("/callback")
    public String callback(AuthCallback callback, HttpServletRequest request) {
        // 1.获取应用的信息
        AuthRequest authRequest = getAuthRequest();

        // 2.登录(根据Code获取AccessToken，根据AccessToken获取用户的信息)
        AuthResponse<AuthUser> response = authRequest.login(callback);
        log.debug(JSONObject.toJSONString(response));

        // 3.判断是否登录成功
        if(response.ok()){
            // 1.用户用第三方应用登录成功后将用户的基本信息存入到AuthUser中
            AuthUser data = response.getData();

            // 2.查询这个第三方用户是否是第一次登录
            ThirdUser thirdUser = userServices.findThirdUser("oauth_id", data.getUuid());

            if (thirdUser == null) {
                // 封装第三方登录的用户基本信息
                thirdUser = new ThirdUser();
                thirdUser.setUsername(data.getUsername());
                thirdUser.setOauthId(data.getUuid());
                log.debug("thirdUser:{}",thirdUser);

                // 第一次登录把第三方用户注册一下
                userServices.registerThirdUser(thirdUser); //username,oauth_id
                thirdUser = userServices.findThirdUser("oauth_id", data.getUuid());

            }
            // 把当前登录的用户放到session中
            UserVo userVo = new UserVo();

            // 将第三方用户信息拷贝到UserVo中
            BeanUtils.copyProperties(thirdUser,userVo);

            log.debug("对象复制:{}",userVo);
            request.getSession().setAttribute(AuthConstants.LOGIN_USER, userVo);

            // 合并购物车
            System.out.println("第三方用户的id为："+userVo.getOauthId());
            shopCarServices.mergeCar(userVo.getOauthId());
            // 跳转到首页
            return "redirect:http://localhost:81/home";

        }
        return "redirect:http://localhost:81/auth/loginUser.html?error=xxxxx";
    }

    /**
     *  返回回调地址
     * @return
     */
    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("7cjQAOVuLpK4wpzYU7i8x4Pl")
                .clientSecret("dTwO5IK5cpkvUGWkciEWp7V2lgWIe90v")
                .redirectUri("http://localhost:81/oauth/callback")
                .build());
    }

}
